package com.yingsheng.bi.hks.config;

import com.yingsheng.bi.hks.template.service.ContextMethodBeanPostProcessor;
import com.yingsheng.bi.hks.web.component.AccessTokenInterceptor;
import com.yingsheng.bi.hks.web.component.HandlerMethodInterceptor;
import com.yingsheng.bi.hks.web.component.HttpLoggerFilter;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerMethodInterceptor());
        registry.addInterceptor(new AccessTokenInterceptor());
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true);
        configurer.favorPathExtension(false);
        configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    @Bean
    public HttpLoggerFilter httpLoggerFilter() {
        return new HttpLoggerFilter();
    }

    @Bean
    public Validator validator() {
        ValidatorFactory factory = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory();
        return factory.getValidator();
    }

    @Bean
    public ContextMethodBeanPostProcessor contextMethodBeanPostProcessor() {
        return new ContextMethodBeanPostProcessor();
    }

}
